<template>
  <div>
    <n-space style="margin-bottom: 10px" justify="space-between">
      <n-space>
        <n-select style="width: 300px" :options = keyWordExtractOptions  v-model:value="extractOption">

        </n-select>
        <n-popconfirm
            @positive-click="gptImagesDescription"
        >
          <template #trigger>
            <n-button type="primary">全部推理</n-button>
          </template>
          全部推理将所有分镜重新推理,包含已经推理出关键词的分镜
        </n-popconfirm>
      </n-space>
    </n-space>
    <n-spin :show="tableLoading" size="large">
      <div class="table-container"
           :style="{ height:( clientHeight - layoutHeaderHeight  - tabsHeight - 50) + 'px', overflowY:`scroll`, scrollbarWidth:`auto`}"
           ref="scrollbarRef">
        <n-table :striped="true" :single-line="false" size="large">
          <n-thead>
            <n-tr>
              <n-th>操作</n-th>
              <n-th>序号</n-th>
              <n-th>原文</n-th>
              <n-th>关键词</n-th>
              <n-th>详细设置</n-th>
              <n-th>骨骼图</n-th>
            </n-tr>
          </n-thead>
          <n-tbody>
            <n-tr v-for="item in dataList.boardList" :key="item.id" style="border-radius: 3px">
              <n-td style="width: 60px;height: 200px">
                <n-button type="error" block @click="deleteBoard(item)">删除</n-button>
                <n-button type="primary" block style="margin-top:5px;" @click="addBoard(item)">插入</n-button>
                <n-button type="info" :loading="item.loading" block style="margin-top:5px;"
                          @click="gptImageDescription(item)">推理
                </n-button>
              </n-td>
              <n-td style="width: 20px;">{{ item.orderNum }}</n-td>
              <n-td style="padding: 2px 2px 2px 2px;width: 700px;">
                <n-grid :x-gap="5" :y-gap="5">
                  <n-grid-item :span="24">
                    <n-card content-style="padding: 5px 5px 5px 5px">
                      <n-button size="small" :type="item.orderNum%2==0?'primary':'warning'" secondary strong block>
                        原文
                      </n-button>
                      <div style="height: 348px;overflow-y: auto">
                        <VueDraggableNext v-model="item.sentenceList" handle=".handle" group="storySentence"
                                          @add="onStorySentenceAdd" @change="onStorySentenceChange">
                          <n-input-group v-if="option.voiceOption" v-for="(sentence,i) in item.sentenceList"
                                         style="margin-top: 5px;">
                            <n-popselect
                                v-if="voiceConfig && voiceConfig.planType==='systemVoice'"
                                @update:value="updateAudioConfig($event,sentence)"
                                v-model:value="sentence.audioConfig.voiceName"
                                :options="option.voiceOption"
                                scrollable
                                trigger="click">
                              <n-button class="handle" type="primary">
                                {{ getVoiceLabelName(sentence.audioConfig) }}
                              </n-button>
                            </n-popselect>

                            <n-button
                                v-if="voiceConfig &&( voiceConfig.planType == 'videoVoice' || voiceConfig.planType == 'uploadVoice')"
                                scrollable
                                type="primary"
                                trigger="click"
                                class="handle">
                              拖拽
                            </n-button>

                            <n-tooltip trigger="hover">
                              <template #trigger>
                                <n-button type="info" @click="sentenceMerge(sentence,'up')">
                                  <n-icon>
                                    <ArrowUp/>
                                  </n-icon>
                                </n-button>
                              </template>
                              向上合并
                            </n-tooltip>
                            <n-input
                                v-model:value="item.sentenceList[i].content"
                                style="width: 450px;"
                                @keydown.enter="handlerEnter(item.sentenceList[i], $event)"
                                @update:value=" item.sentenceList[i].isChange = 1"
                                @blur="updateSentence(item.sentenceList[i])">
                            </n-input>
                            <n-tooltip trigger="hover">
                              <template #trigger>
                                <n-button type="info" @click="sentenceMerge(sentence,'down')">
                                  <n-icon>
                                    <ArrowDown/>
                                  </n-icon>
                                </n-button>
                              </template>
                              往下合并
                            </n-tooltip>
                            <n-popconfirm @positive-click="deleteSentence(sentence)">
                              <template #trigger>
                                <n-button type="warning">
                                  <n-icon>
                                    <CloseSharp/>
                                  </n-icon>
                                </n-button>
                              </template>
                              确定删除该句内容吗？
                            </n-popconfirm>
                          </n-input-group>
                        </VueDraggableNext>
                      </div>
                    </n-card>
                  </n-grid-item>
                </n-grid>
              </n-td>
              <n-td style="padding: 2px 2px 2px 2px;width: 500px;">
                <n-grid>
                  <n-grid-item :span="24">
                    <n-card content-style="padding: 5px 5px 5px 5px">
                      <n-button size="small" :type="item.orderNum%2==0?'primary':'warning'" secondary strong block>
                        关键词
                      </n-button>
                      <div style="height: 348px;overflow-y: auto;margin-top:5px;">
                        <n-input style="height:calc(100% - 2px);width: 100%" type="textarea" v-model:value="item.prompt"
                                 @update:value=" item.isChange = 1"
                                 @blur="updateBoard(item)">

                        </n-input>
                      </div>
                    </n-card>
                  </n-grid-item>
                </n-grid>
              </n-td>

              <n-td style="padding: 2px 2px 2px 2px;width: 700px;">
                <n-grid :x-gap="5" :y-gap="5">
                  <n-grid-item :span="12">
                    <n-card content-style="padding: 5px 5px 5px 5px">
                      <n-button size="small" :type="item.orderNum%2==0?'primary':'warning'" secondary strong block>
                        人物
                      </n-button>
                      <div style="height: 150px;overflow-y: auto">
                        <n-checkbox-group
                            v-model:value="item.characterList"
                            @update:value="characterChecked($event,item)">
                          <n-checkbox
                              v-for="character in option.characterOption"
                              :value="character.id"
                              :label="character.characterName">
                          </n-checkbox>
                        </n-checkbox-group>
                      </div>
                    </n-card>
                  </n-grid-item>
                  <n-grid-item :span="12">
                    <n-card content-style="padding: 5px 5px 5px 5px">
                      <n-button size="small" :type="item.orderNum%2==0?'primary':'warning'" secondary strong block>
                        场景
                      </n-button>
                      <div style="height: 150px;overflow-y: auto">
                        <n-checkbox-group
                            v-model:value="item.sceneList"
                            @update:value="(value, meta)=>sceneChecked(value,meta,item)">
                          <n-checkbox
                              v-for="scene in option.sceneOption"
                              :value="scene.id"
                              :label="scene.sceneName">
                          </n-checkbox>
                        </n-checkbox-group>
                      </div>
                    </n-card>
                  </n-grid-item>
                  <n-grid-item :span="12">
                    <n-card content-style="padding: 5px 5px 5px 5px">
                      <n-button size="small" :type="item.orderNum%2==0?'primary':'warning'" secondary strong block>
                        镜头位置
                      </n-button>
                      <div style="height: 150px;overflow-y: auto">
                        <n-checkbox-group
                            v-model:value="item.cameraList"
                            @update:value="(value, meta)=> cameraChecked(value,meta,item)">
                          <n-checkbox
                              v-for="camera in option.cameraOption"
                              :value="camera.en"
                              :label="camera.zh">
                          </n-checkbox>
                        </n-checkbox-group>
                      </div>
                    </n-card>
                  </n-grid-item>
                  <n-grid-item :span="12">
                    <n-card content-style="padding: 5px 5px 5px 5px">
                      <n-button size="small" :type="item.orderNum%2==0?'primary':'warning'" secondary strong block>
                        拍摄角度
                      </n-button>
                      <div style="height: 150px;overflow-y: auto">
                        <n-checkbox-group
                            v-model:value="item.angleList"
                            @update:value="(value, meta)=> angleChecked(value,meta,item)">
                          <n-checkbox
                              v-for="angle in option.angleOption"
                              :value="angle.en"
                              :label="angle.zh">
                          </n-checkbox>
                        </n-checkbox-group>
                      </div>
                    </n-card>
                  </n-grid-item>
                </n-grid>
              </n-td>

              <n-td style="width: 200px;">
                <n-grid :x-gap="2">
                  <n-grid-item :span="24">
                    <n-button size="small" block type="warning" secondary strong style="margin-bottom: 5px;"
                              @click="cancleOpenPose(item)">
                      撤销
                    </n-button>
                  </n-grid-item>
                  <n-grid-item :span="24">
                    <n-button size="small" block type="primary" secondary strong style="margin-bottom: 5px;"
                              @click="selectedBoard = item ;viewOption.openPoseViewShow = true">
                      选择骨骼图
                    </n-button>
                  </n-grid-item>
                </n-grid>

                <n-card :bordered="false">
                  <template #cover style="height: 400px">
                    <div>
                      <img v-if="item?.poseExampleBackground"
                           :src="fileFunction.getOpenPoseImage(item?.poseExampleBackground)">
                      <img v-if="item?.poseExampleImage"
                           :src="fileFunction.getOpenPoseImage(item?.poseExampleImage)" class="fg-image">
                    </div>
                  </template>
                </n-card>
              </n-td>

            </n-tr>
          </n-tbody>
        </n-table>
      </div>
      <template #description>
        正在努力加载...请耐心等待
      </template>
    </n-spin>
    <n-modal
        v-model:show="progressModal"
        class="custom-card"
        style="width: 500px"
        preset="card"
        title="任务进度"
        size="huge"
        :bordered="false"
        :mask-closable="false"
        @close="getStoryBoardByChapterId"
    >
      <n-space justify="space-around">
        <n-statistic label="当前进度" :value="currentTaskNum">
          <template #prefix>
          </template>
          <template #suffix>
            / {{ dataList.boardList.length }}
          </template>
        </n-statistic>

        <n-statistic label="成功/失败">
          <template #prefix>
            {{ taskStatus.successNum }}
          </template>
          <template #suffix>
            / {{ taskStatus.failNum }}
          </template>
        </n-statistic>
      </n-space>
      <n-progress
          type="line"
          :percentage=" Math.round(currentTaskNum/dataList.boardList.length*100) "
          :height="30"
          :border-radius="5"
          :fill-border-radius="0"
      />
    </n-modal>

    <n-modal
        v-model:show="addModalShow"
        style="width: 600px"
        preset="card"
        title="插入分镜"
        size="huge"
        :bordered="false"
    >
      <n-form>
        <n-h4>您当前在第
          <n-tag type="primary">{{ addNum }}</n-tag>
          分镜插入分镜,新增分镜编号为:
          <n-tag type="primary">{{ addNum + 1 }}</n-tag>
        </n-h4>
        <n-form-item label="原文">
          <n-input type="textarea" style="height: 100px;" v-model:value="editDataForm.content"></n-input>
        </n-form-item>
        <n-form-item label="关键词">
          <n-input type="textarea" style="height: 100px;" v-model:value="editDataForm.prompt"></n-input>
        </n-form-item>
      </n-form>
      <template #footer>
        <n-space justify="end">
          <n-button @click="addModalShow=false">取消</n-button>
          <n-button type="primary" @click="addOrUpdateBoard">确认</n-button>
        </n-space>
      </template>
    </n-modal>

    <n-modal
        v-model:show="updateModalShow"
        style="width: 800px"
        preset="card"
        title="分镜编辑"
        size="huge"
        :bordered="false"
    >
      <n-form>
        <n-row>
          <n-col span="11">
            <n-form-item label="原文描述">
              <n-input type="textarea" disabled style="height: 100px;"
                       v-model:value="editDataFrom_refer.content"></n-input>
            </n-form-item>
          </n-col>
          <n-col span="2">
            <n-space justify="center" style="margin-top: 50px">
              <n-icon :component="ArrowForwardOutline" size="30"></n-icon>
            </n-space>
          </n-col>
          <n-col span="11">
            <n-form-item label="原文描述">
              <n-input type="textarea" style="height: 100px;" v-model:value="editDataForm.content"></n-input>
            </n-form-item>
          </n-col>
        </n-row>
        <n-row>
          <n-col span="11">
            <n-form-item label="画面关键词">
              <n-input type="textarea" disabled style="height: 100px;"
                       v-model:value="editDataFrom_refer.prompt"></n-input>
            </n-form-item>
          </n-col>
          <n-col span="2">
            <n-space justify="center" style="margin-top: 50px">
              <n-icon :component="ArrowForwardOutline" size="30"></n-icon>
            </n-space>
          </n-col>
          <n-col span="11">
            <n-form-item label="画面关键词">
              <n-input type="textarea" style="height: 100px;" v-model:value="editDataForm.prompt"></n-input>
            </n-form-item>
          </n-col>
        </n-row>
        <n-row>
          <n-col span="11">
            <n-form-item label="关键词翻译">
              <n-input type="textarea" disabled style="height: 100px;"
                       v-model:value="editDataFrom_refer.promptEn"></n-input>
            </n-form-item>
          </n-col>
          <n-col span="2">
            <n-space justify="center" style="margin-top: 50px">
              <n-icon :component="ArrowForwardOutline" size="30"></n-icon>
            </n-space>
          </n-col>
          <n-col span="11">
            <n-form-item label="关键词翻译">
              <n-input type="textarea" style="height: 100px;" v-model:value="editDataForm.promptEn"></n-input>
            </n-form-item>
          </n-col>
        </n-row>
      </n-form>
      <template #footer>
        <n-space justify="end">
          <n-button @click="updateModalShow=false">取消</n-button>
          <n-button type="primary" @click="addOrUpdateBoard">确认</n-button>
        </n-space>
      </template>
    </n-modal>


    <n-drawer display-directive="show" v-model:show="viewOption.openPoseViewShow" :width="drawerWidth">
      <n-drawer-content title="从骨骼图选择" closable>
        <OpenPoseView mode="choseOpenPose" :choseOpenPose="chosenOpenPose"></OpenPoseView>
      </n-drawer-content>
    </n-drawer>
  </div>
</template>
<script setup lang="ts">
import {NButton, NImage, NInput, NSelect, NTag, NTreeSelect, TreeOption, useMessage} from 'naive-ui'
import {defineComponent, h, nextTick, onMounted, reactive, ref} from "vue";
import {storyController} from "@/api/story/story.api";
import {storyCharacterController} from '@/api/controller/story/storyCharacterController'
import {storyBoardController} from "@/api/controller/story/storyBoard.api";
import {ArrowDown, ArrowForwardOutline, ArrowUp, CloseSharp} from '@vicons/ionicons5'
import {tagCategoryController} from '@/api/controller/tagcategory/tagCategoryController'
import {storeToRefs} from "pinia";
import {useSystemStore} from "@/store/modules/useSystemStore";
import fileFunction from "@/libs/globalFunction/file";
import {VueDraggableNext} from "vue-draggable-next";
import {storySentenceController} from "@/api/controller/story/storySentenceController.api";
import OpenPoseView from '@/views/pages/configuration/openpose/index.vue'
import CharacterInfoList from "@/views/pages/configuration/character/index.vue";
import {v4 as uuidv4} from "uuid";
import Bus from "@/components/file/box/GlobalUploader/utils/bus";
import {promptControllerApi} from "@/api/prompt/prompt.api";


const message = useMessage()
const story = ref("")
const progressModal = ref(false)
const extractOption = ref('')
const tableLoading = ref(false)
const addOrUpdateLoading = ref(false)
const updateModalShow = ref(false)
const addModalShow = ref(false)
const addNum = ref(0)
const selectedBoard = ref(null)

const drawerWidth = ref(0)


// 当前推理的分镜
const currentTaskNum = ref(1)
// 任务状态
const taskStatus = ref({
  successNum: 0,
  failNum: 0
})


const option = ref({
  voiceOption: [],
  characterOption: [],
  sceneOption: [],
  angleOption: [],
  cameraOption: []
})

const dataList = ref({
  voiceList: [],
  boardList: [],
  characterList: []
})

const viewOption = ref({
  openPoseViewShow: false
})

const voiceConfig = ref(null)


const {
  clientHeight,
  layoutHeaderHeight,
  darkTheme,
  tabsHeight
} = storeToRefs(useSystemStore());

const editDataFrom_refer = reactive({
  content: "",
  prompt: "",
  promptEn: ""
})

const editDataForm = reactive({
  id: "",
  chapterId: "",
  content: "",
  prompt: "",
  promptEn: "",
  orderNum: -1,
  characterName: ""
})


const props = defineProps({
  storyId: {
    type: String,
    required: true
  }
})


// 获取任务列表
const getSetUpOption = () => {
  storyController.getSetUpInfo(props.storyId).then(res => {
    if (res.code === 200) {
      option.value.angleOption = res.data.angleOption
      option.value.cameraOption = res.data.cameraOption
      option.value.sceneOption = res.data.sceneOption
      option.value.characterOption = res.data.characterOption
    }
  })
}


const addBoard = (row: any) => {
  Object.keys(editDataForm).forEach(key => {
    editDataForm[key] = ''
  })
  addNum.value = row.orderNum
  editDataForm.orderNum = row.orderNum + 1
  editDataForm.chapterId = props.storyId
  addModalShow.value = true
}


const getStoryBoardByChapterId = () => {
  tableLoading.value = true
  try {
    const param = {
      storyId: props.storyId,
      page: 0,
      pageSize: 10000
    }
    storyController.getVideoText(param).then(res => {
      if (res.code === 200) {
        dataList.value.boardList = res.data.records
        dataList.value.boardList.forEach((item: any) => {
          if (item.characterName) {
            item.characterList = item.characterName.split(",")
          }
          if (item.sceneName) {
            item.sceneList = item.sceneName.split(",")
          }
          if (item.camera) {
            item.cameraList = item.camera.split(",")
          }
          if (item.angle) {
            item.angleList = item.angle.split(",")
          }
        })
      } else {
        message.error(res.msg)
      }
    })
  } catch (e) {
    message.error(e)
  } finally {
    tableLoading.value = false
  }
}


onMounted(async () => {
  await getStoryPaintConfig(props.storyId)
  await getVoiceList()
  await getSetUpOption()
  getStoryBoardByChapterId()
  getPromptOption()
  drawerWidth.value = window.innerWidth - 300
  window.addEventListener('resize', ev => {
    drawerWidth.value = window.innerWidth - 300;
  });
})


const getVoiceList = async () => {
  await storyController.listVoiceActors(props.storyId).then(res => {
    if (res.code === 200) {
      dataList.value.voiceList = res.data
      dataList.value.voiceList.forEach((item: any) => {
        option.value.voiceOption.push({
          label: item.localName + "|" + item.localeNameZh + "|" + item.age,
          value: item.shortName,
          localName: item.localName
        })
      })
    } else {
      message.error(res.msg)
    }
  })
}

const getVoiceLabelName = (voiceConfig: any) => {
  const selectItems = option.value.voiceOption.filter((item: any) => {
    return item.value == voiceConfig.voiceName
  });
  if (selectItems.length > 0) {
    return selectItems[0].localName
  } else {
    voiceConfig.voiceName = option.value.voiceOption[0].value
    return option.value.voiceOption[0].localName
  }
}


const deleteSentence = (sentence: any) => {
  // 找到分镜
  const storySentence = findSentences(sentence.storyBoardId)
  storySentence.splice(sentence.orderNum, 1)
  storySentenceController.deleteStorySentence(sentence).then(res => {
    if (res.code != 200) {
      message.error(res.msg)
    }
  })
}


/***
 * 按下回车键,分镜内新增句子
 * @param item
 * @param event
 */
const handlerEnter = (item: any, event: any) => {
  const cursorPosition = event.target.selectionStart;
  const inputBeforeCursor = item.content.substring(0, cursorPosition);
  const inputAfterCursor = item.content.substring(cursorPosition);
  const sentences = findSentences(item.storyBoardId)
  const addSentences = {...item}
  addSentences.orderNum = addSentences.orderNum + 1
  addSentences.content = inputAfterCursor
  addSentences.id = uuidv4()
  for (let i = 0; i < sentences.length; i++) {
    const sentence = sentences[i];
    if (sentence.orderNum < item.orderNum) {
      continue
    }
    if (sentence.orderNum == item.orderNum) {
      sentences[i].content = inputBeforeCursor
    } else {
      sentence.orderNum = sentence.orderNum + 1
    }
  }
  sentences.push(addSentences)
  sentences.sort((a: any, b: any) => {
    return a.orderNum - b.orderNum
  })
  let storyBoardIdList = [item.storyBoardId]
  updateSentences(storyBoardIdList, sentences)
}

const findStoryBoard = (storyBoardId: string) => {
  for (let i = 0; i < dataList.value.boardList.length; i++) {
    if (dataList.value.boardList[i].id == storyBoardId) {
      return dataList.value.boardList[i]
    }
  }
}


/**
 * 根据分镜ID查询分镜的句子
 * @param storyBoardId
 */
const findSentences = (storyBoardId: string) => {
  for (let i = 0; i < dataList.value.boardList.length; i++) {
    if (dataList.value.boardList[i].id == storyBoardId) {
      return dataList.value.boardList[i].sentenceList
    }
  }
}

const onStorySentenceChange = (event: any) => {
  if (event.moved) {
    /**
     * 分镜内移动
     */
    let storyBoardIdList = []
    const storyBoardId = event.moved.element.storyBoardId
    storyBoardIdList.push(storyBoardId)
    const sentences = findSentences(storyBoardId)
    sentences.forEach((item: any, index: number) => {
      item.orderNum = index
    })
    updateSentences(storyBoardIdList, sentences)
  }
}

const updateSentences = (storyBoardIdList: any, sentenceList: any) => {
  const param = {
    sentences: sentenceList,
    storyBoardIdList: storyBoardIdList
  }
  storySentenceController.batchHandlerSentences(param).then(res => {
    if (res.code != 200) {
      message.error(res.msg)
    }
  })
}


const onStorySentenceAdd = () => {
  let storyBoardIdList = []
  let needToUpdateSentence = []
  let sentencesNeedToUpdate = findNeedToUpdateStoryBoard()
  console.log(sentencesNeedToUpdate)
  sentencesNeedToUpdate.forEach(uniqueSet => {
    uniqueSet.forEach(value => {
      storyBoardIdList.push(value)
      let sentences = findSentences(value)
      for (let i = 0; i < sentences.length; i++) {
        let sentence = sentences[i]
        sentence.storyBoardId = value
        sentence.orderNum = i
        needToUpdateSentence.push(sentence)
      }
    })
  })
  updateSentences(storyBoardIdList, needToUpdateSentence)
}


const findNeedToUpdateStoryBoard = () => {
  return dataList.value.boardList.map(storyboard => {
    let uniqueSet = new Set(storyboard.sentenceList.map(item => item.storyBoardId));
    if (uniqueSet.size > 1) {
      return uniqueSet
    } else if (uniqueSet.size == 1 && storyboard.id != storyboard.sentenceList[0].storyBoardId) {
      uniqueSet.add(storyboard.id)
      return uniqueSet
    }
    return null; // 如果条件不满足，则返回null
  }).filter(result => result !== null);
}

const nextStep = (callback: any) => {
  storyController.checkStoryBoardPrompt(props.storyId).then(res => {
    if (res.code === 200) {
      callback(true)
    } else {
      message.error(res.data);
      callback(false)
    }
  })
}

const updateAudioConfig = (value: any, sentence: any) => {
  sentence.audioConfig.voiceName = value
  dataList.value.voiceList.forEach((item: any) => {
    if (item.shortName === value) {
      sentence.audioConfig.voiceLocaleName = item.localeName
    }
  })
  updateStorySentence(sentence)
}

const updateStorySentence = (storySentence: any) => {
  storySentenceController.addOrUpdateStorySentence(storySentence).then(res => {
    if (res.code != 200) {
      message.error(res.msg)
    } else {
      storySentence.isChange = '0'
    }
  })
}


const sentenceMerge = (sentence: any, type: string) => {
  const orderNum = sentence.orderNum
  const sentences = findSentences(sentence.storyBoardId)
  if (orderNum == 0 && type == 'up') {
    // 找到上一个分镜
    const storyBoard = findStoryBoard(sentence.storyBoardId)
    if (storyBoard.orderNum == 0) {
      message.error('无法向上合并了')
      return
    }
    let updateSentenceCollection = []
    const lastStoryBoard = dataList.value.boardList[storyBoard.orderNum - 1]
    const preSentences = lastStoryBoard.sentenceList
    // // // 找到合并的句子
    const preSentenceMerge = preSentences[preSentences.length - 1]
    preSentenceMerge.content = preSentenceMerge.content + sentence.content
    sentences.splice(orderNum, 1)
    sentences.forEach((item: any, index: number) => {
      item.orderNum = index
      updateSentenceCollection.push(item)
    })
    preSentences.forEach((item: any, index: number) => {
      item.orderNum = index
      updateSentenceCollection.push(item)
    })
    let storyBoardIdList = [lastStoryBoard.id, storyBoard.id]
    updateSentences(storyBoardIdList, updateSentenceCollection)
  } else if (orderNum == sentences.length - 1 && type == 'down') {
    const storyBoard = findStoryBoard(sentence.storyBoardId)
    if (storyBoard.orderNum == dataList.value.boardList.length - 1) {
      message.info('无法向下合并了')
      return
    }
    let updateSentenceCollection = []
    const nextStoryBoard = dataList.value.boardList[storyBoard.orderNum + 1]
    const nextSentences = nextStoryBoard.sentenceList
    // 找到合并的句子
    const nextSentenceMerge = nextSentences[0]
    nextSentenceMerge.content = sentence.content + nextSentenceMerge.content
    sentences.splice(orderNum, 1)
    sentences.forEach((item: any, index: number) => {
      item.orderNum = index
      updateSentenceCollection.push(item)
    })
    nextSentences.forEach((item: any, index: number) => {
      item.orderNum = index
      updateSentenceCollection.push(item)
    })
    let storyBoardIdList = [nextStoryBoard.id, storyBoard.id]
    updateSentences(storyBoardIdList, updateSentenceCollection)
  } else {
    // 分镜内合并
    if (type == 'up') {
      const preSentence = sentences[orderNum - 1]
      preSentence.content = preSentence.content + sentence.content
      sentences.splice(orderNum, 1)
    } else {
      const nextSentence = sentences[orderNum + 1]
      sentence.content = sentence.content + nextSentence.content
      sentences.splice(orderNum + 1, 1)
    }
    let storyBoardIdList = [sentence.storyBoardId]
    updateSentences(storyBoardIdList, sentences)
  }
}


const characterChecked = (e: any, item: any) => {
  item.characterName = e.join(",")
  updateBoard(item)
}

const sceneChecked = (value: any, meta: any, item: any) => {
  item.sceneName = value.join(",")
  updateBoard(item)
}

const cameraChecked = (value: any, meta: any, item: any) => {
  item.camera = value.join(",")
  updateBoard(item)
}

const angleChecked = (value: any, meta: any, item: any) => {
  item.angle = value.join(",")
  updateBoard(item)
}

const updateBoard = (item: any) => {
  const param = {...item}
  delete param.characterList
  delete param.sceneList
  delete param.cameraList
  delete param.angleList
  storyBoardController.addOrUpdateBoard(param).then(res => {
    if (res.code !== 200) {
      message.error(res.msg)
    }
  })
}

// 更新分镜信息
const addOrUpdateBoard = () => {
  addOrUpdateLoading.value = true
  storyBoardController.addOrUpdateBoard(editDataForm).then(res => {
    addOrUpdateLoading.value = false
    if (res.code === 200) {
      message.success(res.msg)
      getStoryBoardByChapterId()
      addModalShow.value = false
      updateModalShow.value = false
    } else {
      message.error(res.msg)
    }
  })
}


const chosenOpenPose = (openPose: any) => {
  selectedBoard.value.openPose = openPose.id
  selectedBoard.value.poseExampleBackground = openPose.poseExampleBackground
  selectedBoard.value.poseExampleImage = openPose.poseExampleImage
  updateBoard(selectedBoard.value)
  viewOption.value.openPoseViewShow = false
}

/**
 * 删除分镜
 * @param row
 */
const deleteBoard = (row: any) => {
  window.$dialog.warning({
    title: "温馨提醒",
    content: "是否继续删除第(" + row.orderNum + ")号分镜信息？",
    positiveText: "确定",
    negativeText: "取消",
    onPositiveClick: () => {
      storyBoardController.deleteBoard(row.id, row.chapterId).then(res => {
        if (res.code === 200) {
          message.success(res.msg)
          getStoryBoardByChapterId()
        } else {
          message.error(res.msg)
        }
      })
    }
  })
}


const gptImagesDescription = async () => {
  currentTaskNum.value = 0
  taskStatus.value = {
    successNum: 0,
    failNum: 0
  }
  progressModal.value = true
  for (const item of dataList.value.boardList) {
    delete item.characterList
    delete item.sceneList
    delete item.cameraList
    delete item.angleList
    currentTaskNum.value++
    item.content = item.sentenceList.map((item: any) => item.content).join("\n")
    if (!item.content) {
      taskStatus.value.failNum++
      continue
    }
    try {
      const res = await storyController.getImageDescription(item, extractOption.value)
      if (res.code === 200) {
        // 成功
        taskStatus.value.successNum++
      } else {
        // 失败
        taskStatus.value.failNum++
      }
    } catch (e) {
      taskStatus.value.failNum++
    }
  }
  getStoryBoardByChapterId()
}

const gptImageDescription = (row: any) => {
  row.loading = true
  delete row.characterList
  delete row.sceneList
  delete row.cameraList
  delete row.angleList

  row.content = row.sentenceList.map((item: any) => item.content).join("\n")
  console.log(row.content)
  if (!row.content) {
    message.error("分镜内容为空")
    row.loading = false
    return
  }
  storyController.getImageDescription(row, extractOption.value).then(res => {
    if (res.code === 200) {
      getStoryBoardByChapterId()
    } else {
      message.error(res.msg)
    }
  }).finally(() => {
    row.loading = false
  })
}


const cancleOpenPose = (item: any) => {
  item.poseExampleBackground = null
  item.poseExampleImage = null
  item.openPose = null
  updateBoard(item)
}


const updateSentence = (item: any) => {
  if (item.isChange == '1') {
    updateStorySentence(item)
  }
}
const getDataIndex = (orderNum: any) => {
  return dataList.value.boardList.findIndex((item) => item?.orderNum === orderNum)
}

defineExpose({
  nextStep
})


/**
 * 获取该章节的绘画配置
 * @param chapterId
 */
const getStoryPaintConfig = async (chapterId: string) => {
  try {
    const res = await storyController.getStoryPaintConfig(chapterId);
    if (res.code === 200) {
      if (res.data != null) {
        // console.log(res.data.voiceConfig)
        voiceConfig.value = res.data.voiceConfig
      }
    } else {
      message.error(res.msg);
    }
  } catch (error) {
    console.error(error);
  }
}

Bus.on('refreshStoryConfig', () => {
  getStoryPaintConfig(props.storyId)
  getSetUpOption()
  getVoiceList()
  getStoryBoardByChapterId()
})


const keyWordExtractOptions = ref([])
const getPromptOption = () =>{
  promptControllerApi.getGptPromptOption('custom_keyword').then(res => {
    if (res.code === 200) {
      console.log(res.data)
      if(res.data){
        keyWordExtractOptions.value = res.data.map((item: any) => {
          return {
            label: item.promptTitle,
            value: item.id
          }
        })
        extractOption.value = keyWordExtractOptions.value[0].value
      }

      // extractOption.value = res.data
    }
  })

}

</script>
<style scoped>
.fg-image {
  position: absolute; /* 让图片脱离常规文档流，并可进行绝对定位 */
  top: 0;
  left: 0;
  z-index: 2; /* 确保前景图片在上方 */
}
</style>
